package com.wy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //获取核心配置文件的流信息
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            //解析mybatis的核心配置文件
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取SqlSession的方法
    public static SqlSession getSqlSession(){
        // 自动事务控制
        return sqlSessionFactory.openSession(true);
    }
    // 获取dao接口实现类的方法
    public static <T> T getMapper(Class<T> clazz){
        T mapper = getSqlSession().getMapper(clazz);
        return mapper;
    }
    // 关闭sqlSession对象
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }

}
